﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MeleeAttack : MonoBehaviour
{
	public CircleCollider2D attackRange;
	public bool isUnlocked = true;
	public float attackTimer;
	public float coolDown;
	public float damage;

	List<GameObject> nearEnemy = new List<GameObject> ();

	Animator anim;

	// Use this for initialization
	void Start ()
	{
		attackRange.enabled = false;
		attackTimer = 0;
		anim = GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update ()
	{
		anim.ResetTrigger ("Melee");
		if(attackTimer > 0)
		{
			attackTimer -= Time.deltaTime;

			if(attackTimer < 0)
			{
				attackTimer = 0;
				attackRange.enabled = false;
			}
		}

		if(Input.GetKeyDown(KeyCode.X))
		{
			if(attackTimer == 0 && isUnlocked)
			{
				Melee();
				attackTimer = coolDown;
			}

		}
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if(other.gameObject.tag == "Enemy")
		{
			nearEnemy.Add(other.gameObject);
			Debug.Log("entered");
		}
	}

	void OnTriggerExit2D(Collider2D other)
	{
		if(other.gameObject.tag == "Enemy")
		{
			nearEnemy.Remove(other.gameObject);
			Debug.Log("left");
		}
	}

	void Melee()
	{
		Debug.Log ("attacked");

		attackRange.enabled = true;

		Vector3 pos = transform.position;

		for(int i = 0; i < nearEnemy.Count; ++i)
		{
			Vector3 vec = nearEnemy[i].transform.position;
			Vector3 direction = vec - pos;

			Debug.Log ("Health is " + nearEnemy[i].GetComponent<HealthScript>().GetHealth());

			if(Vector3.Dot(direction, transform.right) < 0.3)
			{
				Debug.Log ("attacked");
				nearEnemy[i].GetComponent<HealthScript>().Damage((int)damage);
			}

			Debug.Log ("Health is " + nearEnemy[i].GetComponent<HealthScript>().GetHealth());
		}

		anim.SetTrigger ("Melee");
	}
}
